package com.spring.utils.api_v4.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;

/**
 * 自定义日期处理函数
 */
public class SimpleDate {
    public static String DATE_YYYY_MM_DD = "yyyy-MM-dd";

    public static String DATE_Y_M_DDHHMMSS = "yyyy-MM-dd HH:mm:ss";

    /**
     * 字符串转时间日期
     * @return
     */
    public static Date str2Date(String date) {
        SimpleDateFormat sf = new SimpleDateFormat(DATE_YYYY_MM_DD);
        try {
            return sf.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 字符串转时间
     * @param time
     * @return
     */
    public static Date str2Time(String time) {
        SimpleDateFormat sf = new SimpleDateFormat(DATE_Y_M_DDHHMMSS);
        try {
            return sf.parse(time);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 字符串转整数
     * @param date
     * @param format
     * @return
     */
    public static long convert2long(String date, String format) {
        try {
            if (StringUtils.isNotBlank(date) && StringUtils.isNotBlank(format)) {
                SimpleDateFormat sf = new SimpleDateFormat(format);
                return sf.parse(date).getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0l;
    }

    /**
     * 整数转字符串
     * @param time
     * @param format
     * @return
     */
    public static String convert2String(long time, String format) {
        if (time > 0l && StringUtils.isNotBlank(format)) {
            SimpleDateFormat sf = new SimpleDateFormat(format);
            Date date = new Date(time);
            return sf.format(date);
        }
        return "";
    }

    /**
     * 获取系统当前时间
     * @return
     */
    public static long curTimeMillis() {
        return System.currentTimeMillis();
    }

    /**
     * 时间转换
     * @param date
     * @return
     */
    public static LocalDate date2LocalDate(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

        /**
         * 计算年龄
         * @param birthday
         * @return
         */
    public static int calculateAge(String birthday) {
        LocalDate birth = date2LocalDate(str2Date(birthday));
        LocalDate now = date2LocalDate(new Date());
        return Period.between(birth, now).getYears();
    }
}
